<template>
  <div class="data">
    <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }">
      <a-row justify="space-between">
        <a-col :span="6" :xxl="6" :xl="12" :lg="12">
          <a-form-item label="id" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-decorator="['id', { initialValue: '' }]" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="6" :xxl="6" :xl="12" :lg="12">
          <a-form-item label="名称" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-decorator="['name', { initialValue: '' }]" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12" :xxl="12" :xl="24" :lg="24">
          <div style="dispaly: flex;">
            <span style="margin-right:1rem;">时间区间: </span>
            <a-date-picker :inputReadOnly="true" :allowClear="false" v-model="startTime" show-time />
            -
            <a-date-picker :inputReadOnly="true" :allowClear="false" v-model="endTime" show-time />
          </div>
        </a-col>
        <a-col :span="24" class="right">
          <a-form-item>
            <a-space>
              <a-button @click="resetForm">
                重置
              </a-button>
              <a-button :loading="isLoading" key="submit" type="primary" @click="handleQuery">
                查询
              </a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row justify="space-between">
      <a-col :span="22">
        <h3 v-if="currentTitle">详情列表</h3>
        <h3 v-if="!currentTitle">{{ planName }}</h3>
      </a-col>
      <a-col class="right">
        <util-modules @refresh="refreshData" @densityChange="densityChange" />
        <a-button type="primary" @click="handleExcel">
          导出
        </a-button>
      </a-col>
    </a-row>
    <a-table
      class="my-table"
      :loading="isLoading"
      :rowKey="(record) => record.advertId"
      @expand="expand"
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      @change="handleTableChange"
      :size="activeSize"
    >
      <span slot="ctr" slot-scope="_, record">
        {{ record.advertShowPv == 0 ? 0 : ((record.advertValidClick / record.advertShowPv) * 100).toFixed(2) }}%
      </span>
      <span slot="advertPlanName" slot-scope="_, record">
        <a v-if="userType == 0" @click="handlePlanEdit(record.advertId)">{{ record.advertPlanName }}</a>
        <span v-if="userType == 2">{{ record.advertPlanName }}</span>
      </span>
      <span slot="expectIncome" slot-scope="_, record">
        <span>{{ record.expectIncome == 0 ? 0 : (record.expectIncome / 10000).toFixed(2) || 0 }}</span>
      </span>
      <a-table
        :loading="innerIsLoading"
        slot="expandedRowRender"
        slot-scope="record"
        :columns="innerColumns"
        :data-source="record.innerData"
        :pagination="false"
      >
        <span slot="ctr" slot-scope="_, record">
          <span> {{ record.advertShowPv == 0 ? 0 : ((record.advertValidClick / record.advertShowPv) * 100).toFixed(2) }}% </span>
        </span>
        <span slot="expectIncome" slot-scope="_, record">
          <span>{{ (record.expectIncome / 10000).toFixed(2) || 0 }}</span>
        </span>
      </a-table>
      <span slot="actions" slot-scope="_, record">
        <a @click="handleDetail(record)">详细数据</a>
      </span>
    </a-table>
  </div>
</template>

<script>
import 'moment/locale/zh-cn'
import moment from 'moment'
import { toRoute, getTableSize } from '../../lib/utils'
import UtilModules from '_c/UtilModules.vue'
import { columns, newArr, innerColumns } from './Date'
import { getAdvertPlanData, getAdvertPlanDataDay } from '@/api/Advertising/api'
import { exportExcel } from '../../lib/exportExcel'
export default {
  name: 'Data',
  components: {
    UtilModules,
  },
  data() {
    return {
      activeSize: '',
      startTime: moment(moment().format('YYYY-MM-DD')),
      endTime: moment(moment().format('YYYY-MM-DD')).add(1, 'days'),
      columns: [],
      data: [],
      innerData: [],
      innerColumns,
      isLoading: false,
      innerIsLoading: false,
      form: this.$form.createForm(this, { name: 'data' }),
      pagination: {
        defaultPageSize: 100,
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: (total) => `总共  ${total} 条`, // 显示总数
      },
      userType: 0,
      currentTitle: true,
      planName: '',
      id: '',
    }
  },
  mounted() {
    const { id, planType, planName } = this.$route.query
    if (id) {
      this.currentTitle = false
      this.planName = planName
      this.id = id
    }
    this.advertPlanData({ id, planType, planName })
    this.tableSplit()
  },
  methods: {
    /**
     * @func 刷新数据
     */
    refreshData() {
      this.advertPlanData()
    },
    /**
     * @func 表格密度
     */
    densityChange(value) {
      const { tableSize } = this.$store.state
      this.activeSize = getTableSize(value, tableSize)
    },
    /**
     * @func 表格权限切分
     */
    async tableSplit() {
      this.userType = localStorage.getItem('userType')
      if (localStorage.getItem('userType') == 2) {
        this.columns = newArr
      } else {
        this.columns = columns
      }
    },
    /**
     * @func 计划详情
     */
    handlePlanEdit(id) {
      // toRoute(this, `plan-edit/${id}`)
      toRoute(this, `plan-edit?id=${id}`)
    },
    /**
     * @func 表格改变时
     */
    async handleTableChange(pagination) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.advertPlanData({ pageNo: pagination.current, pageSize: pagination.pageSize })
    },
    /**
     * @func 列表数据
     */
    async advertPlanData(param) {
      this.isLoading = true
      try {
        const { list, count } = await getAdvertPlanData({ ...param })
        const pager = { ...this.pagination }
        pager.total = count
        this.isLoading = false
        if (list) {
          this.data = list ?? []
        }
        this.pagination = pager
      } catch (err) {
        this.isLoading = false
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 嵌套列表数据
     */
    async advertPlanDataDay(param) {
      this.innerIsLoading = true
      try {
        const innerData = await getAdvertPlanDataDay({ ...param })
        this.innerIsLoading = false
        innerData.map((item) => {
          item.computeTime = moment(item.computeTime).format('YYYY-MM-DD')
        })
        if (innerData.length) {
          const adId = innerData[0].advertId
          const i = this.data.findIndex((item) => {
            return item.advertId === adId
          })
          this.data = [...this.data.slice(0, i), { ...this.data[i], innerData: innerData }, ...this.data.slice(i + 1)]
          console.log(this.data)
        }
      } catch (err) {
        this.innerIsLoading = false
        this.$msgErr(err.message)
      }
    },
    handleDetail(record) {
      const { advertId: id, advertPlanName } = record
      this.$router.push({
        path: `/data-detail?id=${id}&advertPlanName=${advertPlanName}`,
      })
    },
    moment,
    /**
     * 查询数据
     */
    handleQuery(e) {
      e.preventDefault()
      const id = this.id
      this.form.validateFields((err, fieldsValue) => {
        if (!err) {
          for (let items in fieldsValue) {
            if (!fieldsValue[items]) {
              fieldsValue[items] = ''
            }
          }
          console.log(fieldsValue)
          const startTime = moment(this.startTime).valueOf()
          const endTime = moment(this.endTime).valueOf()
          const values = {
            startTime,
            endTime,
            ...fieldsValue,
            id: id == '' ? fieldsValue['id'] : id,
          }
          this.advertPlanData(values)
        }
      })
    },
    /**
     * 重置表单
     */
    resetForm() {
      const id = this.id
      this.form.resetFields()
      this.startTime = moment(moment().format('YYYY-MM-DD'))
      this.endTime = moment(moment().format('YYYY-MM-DD')).add(1, 'days')
      this.advertPlanData({ id })
    },
    /**
     * 导出表格
     */
    handleExcel() {
      exportExcel(this, this.columns, 'actions', this.data, '广告计划数据')
      console.log('导出表格')
    },
    /**
     * @func 展开时调用
     */
    expand(_, record) {
      const { advertId: id } = record

      const startTime = moment(moment(this.startTime).format('YYYY-MM-DD')).valueOf()
      const endTime = moment(moment(this.endTime).format('YYYY-MM-DD')).valueOf()
      this.advertPlanDataDay({ id, startTime, endTime })
    },
  },
}
</script>
<style lang="scss" scoped>
.my-table {
  margin-top: 20px;
}
.right {
  display: flex;
  flex-direction: row-reverse;
  padding-right: 20px;
}
.rights {
  display: flex;
  flex-direction: row-reverse;
}
</style>
